#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import smtplib
from email.mime.text import MIMEText
from email.header import Header

from mie.cmdsplit import cmdSplit

import sys
import smtplib
import mimetypes

from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.header import Header


class MieMail:
    def __init__(self, subject=None, fr=None, to=None):
        if isinstance(to, str):
            to = [to]

        self.subject = subject
        self.fr = fr
        self.to = to

        self.msg = MIMEMultipart()
        self.msg["Subject"] = subject
        self.msg["From"] = fr
        self.msg["To"] = ", ".join(to)

    def setSmtp(self, host, port, user, passwd):
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd

    def setContent(self, content, subtype=None):
        subtype = subtype or "html"
        txt = MIMEText(content, _subtype=subtype)
        self.msg.attach(txt)

    def getType(self, path):
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            ctype = "application/octet-stream"
        return ctype.split("/", 1)

    def attText(self, data, filename):
        mtype, stype = self.getType(filename)
        a = MIMEText(data, "base64", "gbk")
        a["Content-Type"] = stype
        a.add_header(
            "Content-Disposition", "attachment", filename=("gbk", "", filename)
        )
        self.msg.attach(a)

    def attImage(self, data, filename):
        a = MIMEImage(data)
        a.add_header(
            "Content-Disposition", "attachment", filename=("gbk", "", filename)
        )
        self.msg.attach(a)

    def send(self, debug=0):
        server = smtplib.SMTP_SSL(self.host, self.port)
        server.set_debuglevel(debug)
        server.login(self.user, self.passwd)
        resp = server.sendmail(self.fr, self.to, self.msg.as_string())
        server.quit()
        return resp


if __name__ == "__main__":

    def help():
        print(
            "Usage: mailtan.py -debug --fr from --to toList --s subject --c content --f file"
        )
        sys.exit(0)

    if "--help" in sys.argv:
        help()

    cmd = cmdSplit(sys.argv)
    fr = cmd.opts_nth("fr", 0)
    to = cmd.opts_nth("to", 0)
    s = cmd.opts_nth("s", 0)
    c = cmd.opts_nth("c", 0)
    f = cmd.opts_nth("f", 0)
    debug = cmd.opts_nth("debug", 0)

    if not fr or not to:
        help()

    to = to.split(",")
    content = c
    if f:
        content = open(f).read()

    smtp_ssl_host = "smtp.exmail.qq.com"
    smtp_ssl_port = 465

    username = "devhelper@berrybit.cn"
    password = "all4ONE"

    fr = username

    mm = MieMail(s, fr, to)
    mm.setSmtp(smtp_ssl_host, smtp_ssl_port, username, password)
    mm.setContent(content)
    mm.send(debug)
